"""Find out what installed MacPorts ports have dependencies and what they are."""

import subprocess
from sys import stdout

print 'Getting ports list ...',
stdout.flush()
installed_ports = subprocess.Popen('port installed', shell=True,
                                    stdout=subprocess.PIPE)
installed_ports.wait()
print 'done.'
unfiltered_ports_list = (x.strip() for x in installed_ports.stdout.readlines())
ports_list = [(x.split(' @')[0] if x.endswith('(active)') else x) for x in
                unfiltered_ports_list if '@' in x]
independents = set()
dependencies = {}
print 'Finding out dependencies',
stdout.flush()
for port in ports_list:
    dependencies_proc = subprocess.Popen('port dependents %s' % port, shell=True,
                                         stdout=subprocess.PIPE)
    dependencies_proc.wait()
    print '.',
    result = dependencies_proc.stdout.read()
    if 'no dependents' in result:
        independents.add(port)
    else:
        dependents = [x.strip() for x in result.splitlines()]
        dependents = [x.split(' depends')[0] for x in dependents]
        for dependent in dependents:
            if dependent not in dependencies:
                dependencies[dependent] = set()
            dependencies[dependent].add(port)
else:
    print 'done'

print
for independent in sorted(independents):
    print independent
    if independent in dependencies:
        print '\t', dependencies[independent]
